//
//  SWBookPageEditor.swift
//  ChildStory
//
//  Created by linhan on 2017/1/7.
//  Copyright © 2017年 Aiya. All rights reserved.
//

import Foundation
import UIKit

protocol SWBookPageEditorDelegate:NSObjectProtocol
{
    func bookPageEditor(editor:SWBookPageEditor, didScrollToIndex index: Int)
    
}

class SWBookPageEditor: UIView,UIPageViewControllerDelegate,UIPageViewControllerDataSource
{
    var currentIndex:Int = 0{
        didSet{
            if currentIndex != oldValue
            {
                delegate?.bookPageEditor(editor: self, didScrollToIndex: currentIndex)
            }
        }
    }
    
    weak var delegate:SWBookPageEditorDelegate?
    
    private var _pages:[SWPage] = []
    
    
    //左边两个 跟 右边 两个用于轮换
    private let VCCacheCount:Int = 3
    private let PageCountPerUnit:Int = 1
    
    private var _pageController:UIPageViewController?
    private var _viewControllers:[UIViewController] = []
    private var _cachedViewControllers:[UIViewController] = []
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setup()
    {
        for i in 0..<VCCacheCount
        {
            let detailViewController:SWPageViewController = SWPageViewController()
            detailViewController.page = _pages.valueAt(i)
            _cachedViewControllers.append(detailViewController)
            //_viewControllers.append(detailViewController)
        }
        
        _pageController = UIPageViewController(transitionStyle: .pageCurl, navigationOrientation: .horizontal, options: nil)
        _pageController?.dataSource = self
        _pageController?.delegate = self
        
        
        if let pageView = _pageController?.view
        {
            pageView.frame = bounds
            addSubview(pageView)
        }
        
        
    }
    
    //是否允许滚动
    var isScrollEnabled:Bool = true{
        didSet{
            if let gestureRecognizers = _pageController?.gestureRecognizers
            {
                gestureRecognizers.filter({$0 is UIPanGestureRecognizer}).valueAt(0)?.isEnabled = isScrollEnabled
                gestureRecognizers.filter({$0 is UITapGestureRecognizer}).valueAt(0)?.isEnabled = isScrollEnabled
            }
        }
    }
    
    func reloadData(pages:[SWPage], index:Int = 0)
    {
        _pages = pages
        currentIndex = max(min(index, pages.count - 1), 0)
        
        _viewControllers.removeAll()
        for i in 0..<min(pages.count, _cachedViewControllers.count)
        {
            _viewControllers.append(_cachedViewControllers[i])
        }
        
        var beginIndex:Int = currentIndex - PageCountPerUnit
        if (currentIndex == 0)
        {
            beginIndex = 0
        }
        else if (currentIndex >= _pages.count - PageCountPerUnit)
        {
            beginIndex = _pages.count - _viewControllers.count
        }
        
        for (i, viewController) in _viewControllers.enumerated()
        {
            (viewController as? SWPageViewController)?.page = _pages.valueAt(i + beginIndex)
        }
        
        beginIndex = PageCountPerUnit
        if index == 0
        {
            beginIndex = 0
        }
        else if index == _pages.count - PageCountPerUnit
        {
            beginIndex = _viewControllers.count - PageCountPerUnit
        }
        
        var viewControllers:[UIViewController]? = []
        if let firstPage = _viewControllers.valueAt(beginIndex)
        {
            viewControllers?.append(firstPage)
        }
        
        _pageController?.setViewControllers(viewControllers, direction: .forward, animated: false, completion: nil)
    }
    
    //跳转到某页
    func jumbIndex(index target:Int, animated:Bool = false)
    {
        let newIndex:Int = max(min(target, _pages.count - 1), 0)
        if newIndex != currentIndex
        {
            let vcCount = _viewControllers.count
            let direction:UIPageViewControllerNavigationDirection = newIndex > currentIndex ? .forward : .reverse
            currentIndex = newIndex
            let beginIndex:Int = min(max(0, currentIndex - PageCountPerUnit), _pages.count - vcCount)
            
            for (i, viewController) in _viewControllers.enumerated()
            {
                let bIndex = beginIndex + i
                if let page = _pages.valueAt(bIndex)
                {
                    (viewController as? SWPageViewController)?.page = page
                }
            }
            
            var aIndex:Int = PageCountPerUnit
            if currentIndex == 0
            {
                aIndex = 0
            }
            else if currentIndex == _pages.count - PageCountPerUnit
            {
                aIndex = _viewControllers.count - PageCountPerUnit
            }
            
            var viewControllers:[UIViewController]? = []
            if let firstPage = _viewControllers.valueAt(aIndex)
            {
                viewControllers?.append(firstPage)
            }
            _pageController?.setViewControllers(viewControllers, direction: direction, animated: animated, completion: nil)
        }
        
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController?
    {
        guard let index = _viewControllers.index(of: viewController) else
        {
            return nil
        }
        return _viewControllers.valueAt(index - 1)
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController?
    {
        guard let index = _viewControllers.index(of: viewController) else
        {
            return nil
        }
        return _viewControllers.valueAt(index + 1)
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool)
    {
        if let currnetViewController = pageViewController.viewControllers?.last, completed
        {
            let index = _viewControllers.index(of: currnetViewController) ?? -1
            
            // 处理四种特殊情况
            if (currentIndex == 0) {
                if (index == 1) {
                    currentIndex += 1
                }
                return;
            }
            if (currentIndex == 1 && index == 0) {
                currentIndex -= 1;
                return;
            }
            if (currentIndex == _pages.count - 1) {
                if (index == 1) {
                    currentIndex -= 1;
                }
                return;
            }
            if (currentIndex == _pages.count - 2 && index == 2) {
                currentIndex += 1;
                return;
            }
            
            
            if (index == 2)
            {  // 往下翻
                currentIndex += 1;
                if (currentIndex + 1 > _pages.count - 1) {
                    return;
                }
                
                if let detailViewController = _viewControllers.removeAtIndexSafely(0),
                    let page = _pages.valueAt(currentIndex + 1)
                {
                    (detailViewController as? SWPageViewController)?.page = page
                    _viewControllers.insert(detailViewController, at: _viewControllers.count)
                }
            }
            else if (index == 0) // 往上翻
            {
                currentIndex -= 1;
                if (currentIndex - 1 < 0) {
                    return;
                }
                
                if let detailViewController = _viewControllers.removeAtIndexSafely(2),
                    let page = _pages.valueAt(currentIndex - 1)
                {
                    (detailViewController as? SWPageViewController)?.page = page
                    _viewControllers.insert(detailViewController, at: 0)
                }
            }
            
            
        }//end completed
    }
    
    
    
    
    
}
